package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Result;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.utils.OssUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 管理员业务处理
 **/
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private OssUtil ossUtil;

    @Value("${oss.bucketUrl}")
    private String OSS_BUCKET_URL;

    @Resource
    @Qualifier("taskExecutor")
    private Executor taskExecutor;


    /**
     * 新增
     */
    public void registerForUser(User user) {

        User newUser = userMapper.selectByUsername(user.getUsername());

        if (newUser!=null) {
            throw new CustomException("用户已存在！");
        }else {
            userMapper.insert(user);
        }
    }


    /**
     * 删除
     */
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /**
     * 修改
     */
    public void updateByUId(User user) {
        userMapper.updateByUId(user);
    }

    /**
     * 根据ID查询
     */
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }


    /**
     * 分页查询所有User用户信息
     */
    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll();
        return new PageInfo<>(list);
    }

    /**
     * 登录
     */
    public User login(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException("用户不存在");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException("账号或密码错误");
        }
        return dbUser;
    }

    /**
     * 修改密码
     * 先验证一下输入的原密码是否正确，如果正确，则修改密码为新密码
     */
    public void updatePassword(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException("用户不存在");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException("原密码错误");
        }
        dbUser.setPassword(user.getNewPassword());
        userMapper.updateByUId(dbUser);
    }

    public Result uploadUserAvatar(Integer  uid, MultipartFile file) throws IOException {
        String avatar_url = ossUtil.uploadImage(file,"avatarImg");

        User user = userMapper.selectById(uid);
        int update = userMapper.updateAvatarByUid(user.getUid(),avatar_url);

        CompletableFuture.runAsync(() ->{
            if(user.getAvatar().startsWith(OSS_BUCKET_URL)){
                String fileName = user.getAvatar().substring(OSS_BUCKET_URL.length());

                ossUtil.deleteFiles(fileName);
            }
        },taskExecutor);
        return Result.Response(200,"上传头像成功",avatar_url);
    }

}